<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>班级积分管理与排名系统</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                        secondary: '#10B981',
                        danger: '#EF4444',
                        neutral: '#6B7280',
                    },
                    animation: {
                        'slide-up': 'slideUp 0.3s ease-out',
                        'fade-in': 'fadeIn 0.3s ease-out',
                    },
                    keyframes: {
                        slideUp: {
                            '0%': { transform: 'translateY(20px)', opacity: '0' },
                            '100%': { transform: 'translateY(0)', opacity: '1' },
                        },
                        fadeIn: {
                            '0%': { opacity: '0' },
                            '100%': { opacity: '1' },
                        }
                    }
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .card-hover {
                @apply transition-all duration-300 hover:shadow-lg hover:-translate-y-1;
            }
            .btn-effect {
                @apply transform transition-all duration-200 hover:scale-105 active:scale-95;
            }
            .podium-1 {
                @apply bg-yellow-100 border-yellow-300;
            }
            .podium-2 {
                @apply bg-gray-100 border-gray-300;
            }
            .podium-3 {
                @apply bg-orange-100 border-orange-300;
            }
        }
    </style>
</head>
<body class="bg-gray-50 text-gray-800 min-h-screen">
    <!-- 登录界面 -->
    <div id="loginScreen" class="min-h-screen flex items-center justify-center p-4 bg-gradient-to-br from-blue-50 to-indigo-50">
        <div class="bg-white rounded-xl shadow-xl p-8 w-full max-w-md animate-slide-up">
            <div class="text-center mb-6">
                <div class="w-16 h-16 bg-primary/10 rounded-full flex items-center justify-center mx-auto mb-4">
                    <i class="fa fa-graduation-cap text-2xl text-primary"></i>
                </div>
                <h2 class="text-2xl font-bold text-gray-800">班级积分管理系统</h2>
                <p class="text-gray-500 mt-2">请输入密码登录</p>
            </div>
            
            <div class="space-y-4">
                <div>
                    <label for="loginPassword" class="block text-gray-600 mb-2">登录密码</label>
                    <div class="relative">
                        <input 
                            type="password" 
                            id="loginPassword" 
                            placeholder="请输入密码" 
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
                        >
                        <button id="toggleLoginPassword" class="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600 transition-colors">
                            <i class="fa fa-eye-slash"></i>
                        </button>
                    </div>
                </div>
                
                <div id="loginError" class="text-danger text-sm hidden animate-fade-in"></div>
                
                <button id="loginBtn" class="w-full bg-primary hover:bg-primary/80 text-white py-3 rounded-lg transition-all duration-300 font-medium btn-effect">
                    登录
                </button>
                
                <button id="forgotPasswordBtn" class="w-full text-gray-500 hover:text-primary transition-colors duration-200 mt-2">
                    忘记密码?
                </button>
            </div>
        </div>
    </div>

    <!-- 忘记密码模态框 -->
    <div id="forgotPasswordModal" class="fixed inset-0 bg-black/50 flex items-center justify-center p-4 hidden">
        <div class="bg-white rounded-xl shadow-lg p-6 w-full max-w-md animate-slide-up">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-xl font-semibold text-gray-800">忘记密码</h3>
                <button id="closeForgotPasswordModal" class="text-gray-400 hover:text-gray-600 transition-colors">
                    <i class="fa fa-times"></i>
                </button>
            </div>
            
            <div class="space-y-4">
                <p class="text-gray-600">请输入教师验证口令以重置密码访问权限</p>
                
                <div>
                    <label for="teacherCode" class="block text-gray-600 mb-2">教师口令</label>
                    <input 
                        type="text" 
                        id="teacherCode" 
                        placeholder="请输入教师口令" 
                        class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
                    >
                </div>
                
                <div id="forgotPasswordError" class="text-danger text-sm hidden animate-fade-in"></div>
                
                <button id="verifyTeacherCodeBtn" class="w-full bg-primary hover:bg-primary/80 text-white py-3 rounded-lg transition-all duration-300 font-medium btn-effect">
                    验证并登录
                </button>
            </div>
        </div>
    </div>

    <!-- 主界面 -->
    <div id="mainScreen" class="container mx-auto px-4 py-8 max-w-7xl hidden">
        <header class="mb-8">
            <div class="flex flex-col sm:flex-row justify-between items-center">
                <div>
                    <h1 class="text-2xl md:text-3xl font-bold text-gray-800 mb-2">班级积分管理与排名系统</h1>
                    <p class="text-gray-500">当前统计周期: <span id="currentPeriodDisplay" class="font-medium"></span></p>
                </div>
                <div class="flex flex-wrap gap-3 mt-4 sm:mt-0">
                    <button id="exportDataBtn" class="bg-neutral hover:bg-neutral/80 text-white px-4 py-2 rounded-lg transition-all duration-300 flex items-center btn-effect">
                        <i class="fa fa-download mr-2"></i> 导出数据
                    </button>
                    <button id="historyBtn" class="bg-neutral hover:bg-neutral/80 text-white px-4 py-2 rounded-lg transition-all duration-300 flex items-center btn-effect">
                        <i class="fa fa-history mr-2"></i> 历史记录
                    </button>
                    <button id="settingsBtn" class="bg-neutral hover:bg-neutral/80 text-white px-4 py-2 rounded-lg transition-all duration-300 flex items-center btn-effect">
                        <i class="fa fa-cog mr-2"></i> 设置
                    </button>
                </div>
            </div>
        </header>

        <!-- 时间范围选择器 -->
        <div class="bg-white rounded-lg shadow-sm p-4 mb-6">
            <div class="flex flex-col md:flex-row items-center justify-between gap-4">
                <div>
                    <h3 class="text-lg font-medium text-gray-800">时间范围</h3>
                    <p class="text-gray-500 text-sm">当前: <span id="timeRangeDisplay" class="font-medium"></span></p>
                </div>
                <div class="flex flex-wrap gap-2">
                    <button data-range="week" class="time-range-btn bg-primary text-white px-4 py-2 rounded-lg transition-all">本周</button>
                    <button data-range="month" class="time-range-btn bg-gray-200 text-gray-700 px-4 py-2 rounded-lg transition-all">本月</button>
                    <button data-range="semester" class="time-range-btn bg-gray-200 text-gray-700 px-4 py-2 rounded-lg transition-all">本学期</button>
                    <button data-range="year" class="time-range-btn bg-gray-200 text-gray-700 px-4 py-2 rounded-lg transition-all">本年度</button>
                </div>
                <div class="flex gap-2">
                    <button id="prevPeriodBtn" class="bg-gray-200 hover:bg-gray-300 text-gray-800 px-3 py-1 rounded-lg transition-all">
                        <i class="fa fa-chevron-left"></i>
                    </button>
                    <button id="nextPeriodBtn" class="bg-gray-200 hover:bg-gray-300 text-gray-800 px-3 py-1 rounded-lg transition-all">
                        <i class="fa fa-chevron-right"></i>
                    </button>
                </div>
            </div>
        </div>

        <!-- 主要内容区域 -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
            <!-- 左侧面板：排名统计 -->
            <div class="lg:col-span-1 space-y-6">
                <!-- 积分统计 -->
                <div class="bg-white rounded-xl shadow-lg p-5 card-hover">
                    <h2 class="text-xl font-semibold text-gray-800 mb-4">积分统计</h2>
                    <div class="h-64">
                        <canvas id="score-chart"></canvas>
                    </div>
                </div>
                
                <!-- 小组排名 -->
                <div class="bg-white rounded-xl shadow-lg p-5 card-hover">
                    <h2 class="text-xl font-semibold text-gray-800 mb-4">小组排名</h2>
                    <div class="h-64">
                        <canvas id="ranking-chart"></canvas>
                    </div>
                </div>
                
                <!-- 添加学生 -->
                <div class="bg-white rounded-xl shadow-lg p-5 card-hover">
                    <h2 class="text-xl font-semibold text-gray-800 mb-4">添加学生</h2>
                    <div class="flex gap-3">
                        <input 
                            type="text" 
                            id="newStudentName" 
                            placeholder="输入学生姓名" 
                            class="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
                        >
                        <select id="newStudentGroup" class="px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all">
                            <option value="">未分组</option>
                        </select>
                        <button id="addStudentBtn" class="bg-primary hover:bg-primary/80 text-white px-4 py-2 rounded-lg transition-all duration-300 btn-effect">
                            <i class="fa fa-plus"></i>
                        </button>
                    </div>
                </div>

                <!-- 小组管理 -->
                <div class="bg-white rounded-xl shadow-lg p-5 card-hover">
                    <h2 class="text-xl font-semibold text-gray-800 mb-4">小组管理</h2>
                    
                    <div class="mb-4">
                        <div class="flex gap-3">
                            <input 
                                type="text" 
                                id="newGroupName" 
                                placeholder="输入小组名称" 
                                class="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
                            >
                            <button id="createGroupBtn" class="bg-primary hover:bg-primary/80 text-white px-4 py-2 rounded-lg transition-all duration-300 btn-effect">
                                创建小组
                            </button>
                        </div>
                    </div>
                    
                    <div id="groupsList" class="space-y-2 max-h-60 overflow-y-auto pr-2">
                        <!-- 小组列表将通过JS动态生成 -->
                    </div>
                </div>
            </div>
            
            <!-- 右侧面板：学生列表和小组列表 -->
            <div class="lg:col-span-2 space-y-6">
                <!-- 视图切换 -->
                <div class="bg-white rounded-xl shadow-sm p-4">
                    <div class="flex border-b">
                        <button id="studentsViewBtn" class="py-2 px-4 border-b-2 border-primary text-primary font-medium">学生列表</button>
                        <button id="groupsViewBtn" class="py-2 px-4 border-b-2 border-transparent text-gray-500 hover:text-gray-700">小组列表</button>
                    </div>
                </div>
                
                <!-- 搜索框 -->
                <div class="bg-white rounded-xl shadow-sm p-4">
                    <div class="relative">
                        <input 
                            type="text" 
                            id="searchInput" 
                            placeholder="搜索学生或小组..." 
                            class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
                        >
                        <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                    </div>
                </div>
                
                <!-- 学生列表 -->
                <div id="students-container" class="bg-white rounded-xl shadow-lg p-5">
                    <!-- 学生列表将通过JS动态生成 -->
                </div>
                
                <!-- 小组列表 -->
                <div id="groups-container" class="bg-white rounded-xl shadow-lg p-5 hidden">
                    <!-- 小组列表将通过JS动态生成 -->
                </div>
            </div>
        </div>
    </div>

    <!-- 学生详情模态框 -->
    <div id="studentDetailModal" class="fixed inset-0 bg-black/50 flex items-center justify-center p-4 hidden">
        <div class="bg-white rounded-xl shadow-lg p-6 w-full max-w-md animate-slide-up">
            <div class="flex justify-between items-center mb-6">
                <h3 class="text-xl font-semibold text-gray-800">学生详情</h3>
                <button id="closeStudentDetailModal" class="text-gray-400 hover:text-gray-600 transition-colors">
                    <i class="fa fa-times"></i>
                </button>
            </div>
            
            <input type="hidden" id="studentDetailId">
            
            <div class="space-y-4">
                <div>
                    <label for="studentDetailName" class="block text-gray-600 mb-2">学生姓名</label>
                    <input 
                        type="text" 
                        id="studentDetailName" 
                        class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
                        readonly
                    >
                </div>
                
                <div>
                    <label for="studentDetailGroup" class="block text-gray-600 mb-2">所属小组</label>
                    <select 
                        id="studentDetailGroup" 
                        class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
                    >
                        <option value="">未分组</option>
                    </select>
                </div>
                
                <div>
                    <label for="studentDetailScore" class="block text-gray-600 mb-2">个人积分</label>
                    <div class="flex items-center">
                        <button id="decreaseStudentScore" class="bg-gray-200 hover:bg-gray-300 text-gray-800 px-3 py-2 rounded-l-lg transition-all duration-300 btn-effect">
                            <i class="fa fa-minus"></i>
                        </button>
                        <input 
                            type="number" 
                            id="studentDetailScore" 
                            class="flex-1 px-4 py-2 border-y border-gray-300 text-center focus:outline-none focus:ring-0 focus:border-primary transition-all"
                        >
                        <button id="increaseStudentScore" class="bg-gray-200 hover:bg-gray-300 text-gray-800 px-3 py-2 rounded-r-lg transition-all duration-300 btn-effect">
                            <i class="fa fa-plus"></i>
                        </button>
                    </div>
                </div>
                
                <div>
                    <label for="scoreChangeReason" class="block text-gray-600 mb-2">积分变动原因</label>
                    <select 
                        id="scoreChangeReason" 
                        class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
                    >
                        <option value="课堂表现良好">课堂表现良好</option>
                        <option value="作业完成优秀">作业完成优秀</option>
                        <option value="积极回答问题">积极回答问题</option>
                        <option value="帮助同学">帮助同学</option>
                        <option value="违反纪律">违反纪律</option>
                        <option value="其他">其他</option>
                    </select>
                </div>
                
                <div class="flex gap-3 mt-6">
                    <button id="saveStudentScoreBtn" class="flex-1 bg-primary hover:bg-primary/80 text-white py-3 rounded-lg transition-all duration-300 font-medium btn-effect">
                        保存积分
                    </button>
                    <button id="deleteStudentBtn" class="flex-1 bg-danger hover:bg-danger/80 text-white py-3 rounded-lg transition-all duration-300 font-medium btn-effect">
                        删除
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 积分规则设置模态框 -->
    <div id="scoreRulesModal" class="fixed inset-0 bg-black/50 flex items-center justify-center p-4 hidden">
        <div class="bg-white rounded-xl shadow-lg p-6 w-full max-w-lg animate-slide-up">
            <div class="flex justify-between items-center mb-6">
                <h3 class="text-xl font-semibold text-gray-800">积分规则设置</h3>
                <button id="closeScoreRulesModal" class="text-gray-400 hover:text-gray-600 transition-colors">
                    <i class="fa fa-times"></i>
                </button>
            </div>
            
            <div id="rulesContainer" class="space-y-4">
                <div class="flex items-center gap-3">
                    <input 
                        type="text" 
                        class="rule-name flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
                        placeholder="规则名称"
                    >
                    <div class="flex items-center gap-2">
                        <input 
                            type="number" 
                            class="rule-score w-24 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
                            placeholder="分值"
                        >
                        <button class="add-rule-btn bg-primary hover:bg-primary/80 text-white px-3 py-2 rounded-lg transition-all duration-300 btn-effect">
                            <i class="fa fa-plus"></i>
                        </button>
                    </div>
                </div>
                
                <div class="space-y-4" id="existingRules">
                    <div class="flex items-center gap-3">
                        <input 
                            type="text" 
                            class="rule-name flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
                            value="课堂表现良好"
                        >
                        <div class="flex items-center gap-2">
                            <input 
                                type="number" 
                                class="rule-score w-24 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
                                value="2"
                            >
                            <button class="delete-rule-btn bg-danger hover:bg-danger/80 text-white px-3 py-2 rounded-lg transition-all duration-300 btn-effect">
                                <i class="fa fa-trash"></i>
                            </button>
                        </div>
                    </div>
                    
                    <div class="flex items-center gap-3">
                        <input 
                            type="text" 
                            class="rule-name flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
                            value="作业完成优秀"
                        >
                        <div class="flex items-center gap-2">
                            <input 
                                type="number" 
                                class="rule-score w-24 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
                                value="3"
                            >
                            <button class="delete-rule-btn bg-danger hover:bg-danger/80 text-white px-3 py-2 rounded-lg transition-all duration-300 btn-effect">
                                <i class="fa fa-trash"></i>
                            </button>
                        </div>
                    </div>
                    
                    <div class="flex items-center gap-3">
                        <input 
                            type="text" 
                            class="rule-name flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
                            value="积极回答问题"
                        >
                        <div class="flex items-center gap-2">
                            <input 
                                type="number" 
                                class="rule-score w-24 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
                                value="1"
                            >
                            <button class="delete-rule-btn bg-danger hover:bg-danger/80 text-white px-3 py-2 rounded-lg transition-all duration-300 btn-effect">
                                <i class="fa fa-trash"></i>
                            </button>
                        </div>
                    </div>
                    
                    <div class="flex items-center gap-3">
                        <input 
                            type="text" 
                            class="rule-name flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
                            value="帮助同学"
                        >
                        <div class="flex items-center gap-2">
                            <input 
                                type="number" 
                                class="rule-score w-24 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
                                value="2"
                            >
                            <button class="delete-rule-btn bg-danger hover:bg-danger/80 text-white px-3 py-2 rounded-lg transition-all duration-300 btn-effect">
                                <i class="fa fa-trash"></i>
                            </button>
                        </div>
                    </div>
                    
                    <div class="flex items-center gap-3">
                        <input 
                            type="text" 
                            class="rule-name flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
                            value="违反纪律"
                        >
                        <div class="flex items-center gap-2">
                            <input 
                                type="number" 
                                class="rule-score w-24 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
                                value="-2"
                            >
                            <button class="delete-rule-btn bg-danger hover:bg-danger/80 text-white px-3 py-2 rounded-lg transition-all duration-300 btn-effect">
                                <i class="fa fa-trash"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="mt-6">
                <div class="flex items-center mb-4">
                    <input type="checkbox" id="allowNegativeScores" class="mr-2">
                    <label for="allowNegativeScores" class="text-gray-600">允许积分出现负值</label>
                </div>
                
                <button id="saveScoreRulesBtn" class="w-full bg-primary hover:bg-primary/80 text-white py-3 rounded-lg transition-all duration-300 font-medium btn-effect">
                    保存积分规则
                </button>
            </div>
        </div>
    </div>

    <!-- 设置模态框 -->
    <div id="settingsModal" class="fixed inset-0 bg-black/50 flex items-center justify-center p-4 hidden">
        <div class="bg-white rounded-xl shadow-lg p-6 w-full max-w-md animate-slide-up">
            <div class="flex justify-between items-center mb-6">
                <h3 class="text-xl font-semibold text-gray-800">系统设置</h3>
                <button id="closeSettingsModal" class="text-gray-400 hover:text-gray-600 transition-colors">
                    <i class="fa fa-times"></i>
                </button>
            </div>
            
            <div class="space-y-4">
                <button id="changePasswordBtn" class="w-full text-left px-4 py-3 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors flex justify-between items-center">
                    <span>修改登录密码</span>
                    <i class="fa fa-chevron-right text-gray-400"></i>
                </button>
                
                <button id="changeTeacherCodeBtn" class="w-full text-left px-4 py-3 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors flex justify-between items-center">
                    <span>修改教师口令</span>
                    <i class="fa fa-chevron-right text-gray-400"></i>
                </button>
                
                <button id="scoreRulesBtn" class="w-full text-left px-4 py-3 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors flex justify-between items-center">
                    <span>积分规则设置</span>
                    <i class="fa fa-chevron-right text-gray-400"></i>
                </button>
                
                <button id="clearDataBtn" class="w-full text-left px-4 py-3 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors flex justify-between items-center text-danger">
                    <span>清空所有数据</span>
                    <i class="fa fa-chevron-right"></i>
                </button>
            </div>
        </div>
    </div>

    <!-- 修改密码模态框 -->
    <div id="changePasswordModal" class="fixed inset-0 bg-black/50 flex items-center justify-center p-4 hidden">
        <div class="bg-white rounded-xl shadow-lg p-6 w-full max-w-md animate-slide-up">
            <div class="flex justify-between items-center mb-6">
                <h3 class="text-xl font-semibold text-gray-800">修改密码</h3>
                <button id="closeChangePasswordModal" class="text-gray-400 hover:text-gray-600 transition-colors">
                    <i class="fa fa-times"></i>
                </button>
            </div>
            
            <div class="space-y-4">
                <!-- 验证方式选择 -->
                <div class="flex border rounded-lg overflow-hidden">
                    <button id="useCurrentPasswordBtn" class="flex-1 py-2 bg-primary text-white">使用当前密码验证</button>
                    <button id="useTeacherCodeBtn" class="flex-1 py-2 bg-gray-200 text-gray-700">使用教师口令验证</button>
                </div>
                
                <!-- 当前密码验证区域 -->
                <div id="currentPasswordSection">
                    <div>
                        <label for="currentPassword" class="block text-gray-600 mb-2">当前密码</label>
                        <div class="relative">
                            <input 
                                type="password" 
                                id="currentPassword" 
                                placeholder="请输入当前密码" 
                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
                            >
                            <button id="toggleCurrentPassword" class="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600 transition-colors">
                                <i class="fa fa-eye-slash"></i>
                            </button>
                        </div>
                    </div>
                </div>
                
                <!-- 教师验证码验证区域 -->
                <div id="teacherCodeSection" class="hidden">
                    <div>
                        <label for="modifyPasswordTeacherCode" class="block text-gray-600 mb-2">教师验证码</label>
                        <div class="relative">
                            <input 
                                type="password" 
                                id="modifyPasswordTeacherCode" 
                                placeholder="请输入教师验证码" 
                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
                            >
                            <button id="toggleModifyTeacherCode" class="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600 transition-colors">
                                <i class="fa fa-eye-slash"></i>
                            </button>
                        </div>
                    </div>
                </div>
                
                <div>
                    <label for="newPassword" class="block text-gray-600 mb-2">新密码</label>
                    <div class="relative">
                        <input 
                            type="password" 
                            id="newPassword" 
                            placeholder="请输入新密码（至少6位）" 
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
                        >
                        <button id="toggleNewPassword" class="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600 transition-colors">
                            <i class="fa fa-eye-slash"></i>
                        </button>
                    </div>
                </div>
                
                <div>
                    <label for="confirmPassword" class="block text-gray-600 mb-2">确认新密码</label>
                    <div class="relative">
                        <input 
                            type="password" 
                            id="confirmPassword" 
                            placeholder="请再次输入新密码" 
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
                        >
                        <button id="toggleConfirmPassword" class="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600 transition-colors">
                            <i class="fa fa-eye-slash"></i>
                        </button>
                    </div>
                </div>
                
                <div id="passwordError" class="text-danger text-sm hidden animate-fade-in"></div>
                
                <div class="flex gap-3">
                    <button id="backToSettingsFromPasswordBtn" class="flex-1 bg-gray-200 hover:bg-gray-300 text-gray-800 py-3 rounded-lg transition-all duration-300 font-medium">
                        返回
                    </button>
                    <button id="savePasswordBtn" class="flex-1 bg-primary hover:bg-primary/80 text-white py-3 rounded-lg transition-all duration-300 font-medium btn-effect">
                        保存密码
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 教师口令设置模态框 -->
    <div id="teacherCodeSettingsModal" class="fixed inset-0 bg-black/50 flex items-center justify-center p-4 hidden">
        <div class="bg-white rounded-xl shadow-lg p-6 w-full max-w-md animate-slide-up">
            <div class="flex justify-between items-center mb-6">
                <h3 class="text-xl font-semibold text-gray-800">设置教师口令</h3>
                <button id="closeTeacherCodeSettingsModal" class="text-gray-400 hover:text-gray-600 transition-colors">
                    <i class="fa fa-times"></i>
                </button>
            </div>
            
            <div class="space-y-4">
                <div>
                    <label for="currentTeacherCode" class="block text-gray-600 mb-2">当前教师口令</label>
                    <div class="relative">
                        <input 
                            type="password" 
                            id="currentTeacherCode" 
                            placeholder="请输入当前教师口令" 
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
                        >
                        <button id="toggleCurrentTeacherCode" class="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600 transition-colors">
                            <i class="fa fa-eye-slash"></i>
                        </button>
                    </div>
                </div>
                
                <div>
                    <label for="newTeacherCode" class="block text-gray-600 mb-2">新教师口令</label>
                    <div class="relative">
                        <input 
                            type="password" 
                            id="newTeacherCode" 
                            placeholder="请输入新教师口令（至少6位）" 
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
                        >
                        <button id="toggleNewTeacherCode" class="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600 transition-colors">
                            <i class="fa fa-eye-slash"></i>
                        </button>
                    </div>
                </div>
                
                <div>
                    <label for="confirmTeacherCode" class="block text-gray-600 mb-2">确认新教师口令</label>
                    <div class="relative">
                        <input 
                            type="password" 
                            id="confirmTeacherCode" 
                            placeholder="请再次输入新教师口令" 
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
                        >
                        <button id="toggleConfirmTeacherCode" class="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600 transition-colors">
                            <i class="fa fa-eye-slash"></i>
                        </button>
                    </div>
                </div>
                
                <div id="teacherCodeError" class="text-danger text-sm hidden animate-fade-in"></div>
                <div id="teacherCodeSuccess" class="text-secondary text-sm hidden animate-fade-in"></div>
                
                <div class="flex gap-3">
                    <button id="backToSettingsFromTeacherCodeBtn" class="flex-1 bg-gray-200 hover:bg-gray-300 text-gray-800 py-3 rounded-lg transition-all duration-300 font-medium">
                        返回
                    </button>
                    <button id="saveTeacherCodeBtn" class="flex-1 bg-primary hover:bg-primary/80 text-white py-3 rounded-lg transition-all duration-300 font-medium btn-effect">
                        保存口令
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 历史记录模态框 -->
    <div id="historyModal" class="fixed inset-0 bg-black/50 flex items-center justify-center p-4 hidden">
        <div class="bg-white rounded-xl shadow-lg p-6 w-full max-w-3xl animate-slide-up max-h-[90vh] overflow-hidden flex flex-col">
            <div class="flex justify-between items-center mb-6">
                <h3 class="text-xl font-semibold text-gray-800">积分变动历史记录</h3>
                <button id="closeHistoryModal" class="text-gray-400 hover:text-gray-600 transition-colors">
                    <i class="fa fa-times"></i>
                </button>
            </div>
            
            <div class="flex mb-4">
                <select id="historyFilterType" class="px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all mr-2">
                    <option value="all">全部记录</option>
                    <option value="student">学生记录</option>
                    <option value="group">小组记录</option>
                </select>
                <input 
                    type="text" 
                    id="historySearchInput" 
                    placeholder="搜索学生/小组名称..." 
                    class="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
                >
                <button id="clearHistoryBtn" class="ml-2 bg-danger hover:bg-danger/80 text-white px-4 py-2 rounded-lg transition-all duration-300 btn-effect">
                    清空记录
                </button>
            </div>
            
            <div id="historyContainer" class="flex-1 overflow-y-auto">
                <!-- 历史记录将通过JS动态生成 -->
                <p class="text-gray-500 text-center py-4">暂无积分变动记录</p>
            </div>
        </div>
    </div>

    <!-- 通知组件 -->
    <div id="notification" class="fixed top-4 right-4 bg-gray-800 text-white px-6 py-3 rounded-lg shadow-lg transform translate-x-full transition-transform duration-300 flex items-center">
        <i id="notificationIcon" class="fa fa-check-circle mr-2 text-secondary"></i>
        <span id="notificationMessage"></span>
    </div>

    <script>
        // 数据存储与初始化
        const DataStore = {
            // 初始化本地存储数据
            init() {
                if (!localStorage.getItem('password')) {
                    localStorage.setItem('password', '123456'); // 默认密码
                }
                if (!localStorage.getItem('teacherCode')) {
                    localStorage.setItem('teacherCode', 'admin123'); // 默认教师口令
                }
                if (!localStorage.getItem('students')) {
                    localStorage.setItem('students', JSON.stringify([]));
                }
                if (!localStorage.getItem('groups')) {
                    localStorage.setItem('groups', JSON.stringify([]));
                }
                if (!localStorage.getItem('scoreHistory')) {
                    localStorage.setItem('scoreHistory', JSON.stringify([]));
                }
                if (!localStorage.getItem('scoreRules')) {
                    const defaultRules = {
                        "课堂表现良好": 2,
                        "作业完成优秀": 3,
                        "积极回答问题": 1,
                        "帮助同学": 2,
                        "违反纪律": -2,
                        "其他": 1
                    };
                    localStorage.setItem('scoreRules', JSON.stringify(defaultRules));
                }
                if (!localStorage.getItem('systemSettings')) {
                    const defaultSettings = {
                        allowNegativeScores: true
                    };
                    localStorage.setItem('systemSettings', JSON.stringify(defaultSettings));
                }
                if (!localStorage.getItem('dailyScores')) {
                    localStorage.setItem('dailyScores', JSON.stringify({}));
                }
            },
            
            // 密码相关
            getPassword() {
                return localStorage.getItem('password');
            },
            changePassword(newPassword) {
                localStorage.setItem('password', newPassword);
            },
            
            // 教师口令相关
            getTeacherCode() {
                return localStorage.getItem('teacherCode');
            },
            changeTeacherCode(newCode) {
                localStorage.setItem('teacherCode', newCode);
            },
            
            // 学生相关
            getStudents() {
                return JSON.parse(localStorage.getItem('students') || '[]');
            },
            saveStudents(students) {
                localStorage.setItem('students', JSON.stringify(students));
            },
            addStudent(student) {
                const students = this.getStudents();
                students.push(student);
                this.saveStudents(students);
                return student;
            },
            updateStudent(updatedStudent) {
                const students = this.getStudents();
                const index = students.findIndex(s => s.id === updatedStudent.id);
                if (index !== -1) {
                    students[index] = updatedStudent;
                    this.saveStudents(students);
                    return true;
                }
                return false;
            },
            deleteStudent(studentId) {
                let students = this.getStudents();
                students = students.filter(s => s.id !== studentId);
                this.saveStudents(students);
                
                // 同时从小组中移除
                let groups = this.getGroups();
                groups = groups.map(group => {
                    group.members = group.members.filter(id => id !== studentId);
                    return group;
                });
                this.saveGroups(groups);
                
                return true;
            },
            
            // 小组相关
            getGroups() {
                return JSON.parse(localStorage.getItem('groups') || '[]');
            },
            saveGroups(groups) {
                localStorage.setItem('groups', JSON.stringify(groups));
            },
            createGroup(group) {
                const groups = this.getGroups();
                groups.push(group);
                this.saveGroups(groups);
                return group;
            },
            updateGroup(updatedGroup) {
                const groups = this.getGroups();
                const index = groups.findIndex(g => g.id === updatedGroup.id);
                if (index !== -1) {
                    groups[index] = updatedGroup;
                    this.saveGroups(groups);
                    return true;
                }
                return false;
            },
            deleteGroup(groupId) {
                let groups = this.getGroups();
                groups = groups.filter(g => g.id !== groupId);
                this.saveGroups(groups);
                
                // 将该小组的学生设为未分组
                let students = this.getStudents();
                students = students.map(student => {
                    if (student.groupId === groupId) {
                        student.groupId = '';
                    }
                    return student;
                });
                this.saveStudents(students);
                
                return true;
            },
            
            // 积分历史相关
            getScoreHistory() {
                return JSON.parse(localStorage.getItem('scoreHistory') || '[]');
            },
            addScoreHistory(record) {
                const history = this.getScoreHistory();
                history.push({
                    id: 'hist_' + Date.now(),
                    timestamp: new Date().toISOString(),
                    ...record
                });
                localStorage.setItem('scoreHistory', JSON.stringify(history));
                return record;
            },
            clearScoreHistory() {
                localStorage.setItem('scoreHistory', JSON.stringify([]));
            },
            
            // 积分规则相关
            getScoreRules() {
                return JSON.parse(localStorage.getItem('scoreRules') || '{}');
            },
            saveScoreRules(rules) {
                localStorage.setItem('scoreRules', JSON.stringify(rules));
            },
            
            // 系统设置相关
            getSystemSettings() {
                return JSON.parse(localStorage.getItem('systemSettings') || '{}');
            },
            saveSystemSettings(settings) {
                localStorage.setItem('systemSettings', JSON.stringify(settings));
            },
            
            // 每日积分统计相关
            getDailyScores() {
                return JSON.parse(localStorage.getItem('dailyScores') || '{}');
            },
            updateDailyScore(date, scoreChange) {
                const dailyScores = this.getDailyScores();
                const dateStr = date.toISOString().split('T')[0];
                if (!dailyScores[dateStr]) {
                    dailyScores[dateStr] = 0;
                }
                dailyScores[dateStr] += scoreChange;
                localStorage.setItem('dailyScores', JSON.stringify(dailyScores));
            },
            
            // 清空所有数据
            clearAllData() {
                localStorage.removeItem('students');
                localStorage.removeItem('groups');
                localStorage.removeItem('scoreHistory');
                localStorage.removeItem('dailyScores');
                this.init(); // 重新初始化默认数据
            }
        };

        // 工具函数：生成唯一ID
        function generateId() {
            return Date.now().toString(36) + Math.random().toString(36).substr(2, 5);
        }

        // 工具函数：显示模态框
        function showModal(modalId) {
            document.getElementById(modalId).classList.remove('hidden');
            // 防止背景滚动
            document.body.style.overflow = 'hidden';
        }

        // 工具函数：隐藏模态框
        function hideModal(modalId) {
            document.getElementById(modalId).classList.add('hidden');
            // 恢复背景滚动
            document.body.style.overflow = '';
        }

        // 工具函数：切换密码可见性
        function togglePasswordVisibility(inputId, buttonId) {
            return function() {
                const input = document.getElementById(inputId);
                const button = document.getElementById(buttonId);
                
                if (input.type === 'password') {
                    input.type = 'text';
                    button.innerHTML = '<i class="fa fa-eye"></i>';
                } else {
                    input.type = 'password';
                    button.innerHTML = '<i class="fa fa-eye-slash"></i>';
                }
            };
        }

        // 工具函数：显示通知
        function showNotification(message, type = 'success') {
            const notification = document.getElementById('notification');
            const icon = document.getElementById('notificationIcon');
            const messageEl = document.getElementById('notificationMessage');
            
            messageEl.textContent = message;
            
            // 设置图标
            if (type === 'success') {
                icon.className = 'fa fa-check-circle mr-2 text-secondary';
            } else if (type === 'error') {
                icon.className = 'fa fa-exclamation-circle mr-2 text-danger';
            } else if (type === 'warning') {
                icon.className = 'fa fa-exclamation-triangle mr-2 text-yellow-500';
            }
            
            // 显示通知
            notification.classList.remove('translate-x-full');
            
            // 3秒后隐藏
            setTimeout(() => {
                notification.classList.add('translate-x-full');
            }, 3000);
        }

        // 更新历史记录显示
        function updateHistoryDisplay() {
            const historyContainer = document.getElementById('historyContainer');
            const history = DataStore.getScoreHistory();
            const filterType = document.getElementById('historyFilterType').value;
            const searchTerm = document.getElementById('historySearchInput').value.toLowerCase();
            
            // 过滤历史记录
            let filteredHistory = [...history];
            
            // 按类型过滤
            if (filterType !== 'all') {
                filteredHistory = filteredHistory.filter(record => record.type === filterType);
            }
            
            // 按搜索词过滤
            if (searchTerm) {
                filteredHistory = filteredHistory.filter(record => 
                    record.targetName.toLowerCase().includes(searchTerm)
                );
            }
            
            // 按时间倒序排列
            filteredHistory.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
            
            if (filteredHistory.length === 0) {
                historyContainer.innerHTML = '<p class="text-gray-500 text-center py-4">暂无符合条件的积分变动记录</p>';
                return;
            }
            
            let html = `
                <table class="min-w-full divide-y divide-gray-200">
                    <thead>
                        <tr class="bg-gray-50">
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">时间</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">对象</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">名称</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">变动积分</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">原因</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">当前积分</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
            `;
            
            filteredHistory.forEach(record => {
                const date = new Date(record.timestamp);
                const formattedDate = date.toLocaleString();
                const changeClass = record.change > 0 ? 'text-secondary' : (record.change < 0 ? 'text-danger' : 'text-gray-500');
                const changeText = record.change > 0 ? `+${record.change}` : record.change;
                
                html += `
                    <tr class="hover:bg-gray-50 transition-colors">
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${formattedDate}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${record.type === 'student' ? '学生' : '小组'}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${record.targetName}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm ${changeClass} font-medium">${changeText}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${record.reason}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${record.newScore}</td>
                    </tr>
                `;
            });
            
            html += `
                    </tbody>
                </table>
            `;
            
            historyContainer.innerHTML = html;
        }

        // 初始化积分规则表单
        function initScoreRulesForm() {
            const rules = DataStore.getScoreRules();
            const settings = DataStore.getSystemSettings();
            const existingRulesContainer = document.getElementById('existingRules');
            
            // 清空现有规则
            existingRulesContainer.innerHTML = '';
            
            // 添加保存的规则
            Object.keys(rules).forEach(reason => {
                addRuleInput(reason, rules[reason]);
            });
            
            // 设置允许负分选项
            document.getElementById('allowNegativeScores').checked = settings.allowNegativeScores || false;
            
            // 添加新规则按钮事件
            document.querySelectorAll('.add-rule-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const nameInput = this.closest('.flex').querySelector('.rule-name');
                    const scoreInput = this.closest('.flex').querySelector('.rule-score');
                    
                    const name = nameInput.value.trim();
                    const score = parseInt(scoreInput.value) || 0;
                    
                    if (name) {
                        addRuleInput(name, score);
                        nameInput.value = '';
                        scoreInput.value = '';
                    } else {
                        showNotification('请输入规则名称', 'warning');
                    }
                });
            });
            
            // 删除规则按钮事件委托
            existingRulesContainer.addEventListener('click', function(e) {
                if (e.target.closest('.delete-rule-btn')) {
                    const ruleEl = e.target.closest('.flex');
                    if (document.querySelectorAll('#existingRules .flex').length > 1) {
                        ruleEl.remove();
                    } else {
                        showNotification('至少保留一条规则', 'warning');
                    }
                }
            });
        }

        // 添加规则输入框
        function addRuleInput(name, score) {
            const existingRulesContainer = document.getElementById('existingRules');
            
            const ruleEl = document.createElement('div');
            ruleEl.className = 'flex items-center gap-3';
            ruleEl.innerHTML = `
                <input 
                    type="text" 
                    class="rule-name flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
                    value="${name}"
                >
                <div class="flex items-center gap-2">
                    <input 
                        type="number" 
                        class="rule-score w-24 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
                        value="${score}"
                    >
                    <button class="delete-rule-btn bg-danger hover:bg-danger/80 text-white px-3 py-2 rounded-lg transition-all duration-300 btn-effect">
                        <i class="fa fa-trash"></i>
                    </button>
                </div>
            `;
            
            existingRulesContainer.appendChild(ruleEl);
        }

        // 保存积分规则
        function saveScoreRules() {
            const ruleElements = document.querySelectorAll('#existingRules .flex');
            const rules = {};
            
            ruleElements.forEach(el => {
                const name = el.querySelector('.rule-name').value.trim();
                const score = parseInt(el.querySelector('.rule-score').value) || 0;
                
                if (name) {
                    rules[name] = score;
                }
            });
            
            // 保存系统设置（允许负分）
            const settings = DataStore.getSystemSettings();
            settings.allowNegativeScores = document.getElementById('allowNegativeScores').checked;
            DataStore.saveSystemSettings(settings);
            
            DataStore.saveScoreRules(rules);
            
            // 更新积分变动原因下拉框
            const scoreChangeReason = document.getElementById('scoreChangeReason');
            const currentValue = scoreChangeReason.value;
            
            scoreChangeReason.innerHTML = '';
            Object.keys(rules).forEach(reason => {
                const option = document.createElement('option');
                option.value = reason;
                option.textContent = reason;
                if (option.value === currentValue) {
                    option.selected = true;
                }
                scoreChangeReason.appendChild(option);
            });
            
            hideModal('scoreRulesModal');
            showNotification('积分规则已保存');
        }

        // 导出数据
        function exportData() {
            const students = DataStore.getStudents();
            const groups = DataStore.getGroups();
            const history = DataStore.getScoreHistory();
            
            // 格式化数据为文本
            let dataText = "班级积分管理系统数据导出\n";
            dataText += "导出时间: " + new Date().toLocaleString() + "\n\n";
            
            // 学生数据
            dataText += "===== 学生数据 =====\n";
            if (students.length > 0) {
                students.forEach((student, index) => {
                    // 查找学生所属小组
                    let groupName = '未分组';
                    groups.forEach(group => {
                        if (group.members && group.members.includes(student.id)) {
                            groupName = group.name;
                        }
                    });
                    dataText += `${index + 1}. ${student.name} - 积分: ${student.score} - 所属小组: ${groupName}\n`;
                });
            } else {
                dataText += "无学生数据\n";
            }
            dataText += "\n";
            
            // 小组数据
            dataText += "===== 小组数据 =====\n";
            if (groups.length > 0) {
                groups.forEach((group, index) => {
                    // 计算小组总积分
                    let totalScore = 0;
                    students.forEach(student => {
                        if (student.groupId === group.id) {
                            totalScore += student.score;
                        }
                    });
                    dataText += `${index + 1}. ${group.name} - 总积分: ${totalScore} - 成员数: ${group.members ? group.members.length : 0}\n`;
                });
            } else {
                dataText += "无小组数据\n";
            }
            dataText += "\n";
            
            // 最近10条历史记录
            dataText += "===== 最近10条积分变动记录 =====\n";
            if (history.length > 0) {
                const recentHistory = history.slice(-10).reverse();
                recentHistory.forEach((record, index) => {
                    const date = new Date(record.timestamp).toLocaleString();
                    const type = record.type === 'student' ? '学生' : '小组';
                    const target = record.targetName;
                    const change = record.change > 0 ? `+${record.change}` : record.change;
                    
                    dataText += `${index + 1}. [${date}] ${type}: ${target} - 积分变动: ${change} - 原因: ${record.reason || '无'}\n`;
                });
            } else {
                dataText += "无积分变动记录\n";
            }
            
            // 创建并下载文件
            const blob = new Blob([dataText], { type: 'text/plain' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `班级积分数据_${new Date().toLocaleDateString().replace(/\//g, '-')}.txt`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
            
            showNotification('数据导出成功');
        }

        // 初始化积分趋势图
        let scoreChart = null;
        function initScoreChart() {
            const ctx = document.getElementById('score-chart').getContext('2d');
            const dailyScores = DataStore.getDailyScores();
            
            // 按日期排序
            const sortedDates = Object.keys(dailyScores).sort((a, b) => new Date(a) - new Date(b));
            const labels = sortedDates.map(date => {
                const d = new Date(date);
                return `${d.getMonth() + 1}/${d.getDate()}`;
            });
            const data = sortedDates.map(date => dailyScores[date]);
            
            // 销毁现有图表
            if (scoreChart) {
                scoreChart.destroy();
            }
            
            // 创建新图表
            scoreChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: labels,
                    datasets: [{
                        label: '每日积分变化',
                        data: data,
                        backgroundColor: 'rgba(59, 130, 246, 0.2)',
                        borderColor: 'rgba(59, 130, 246, 1)',
                        borderWidth: 2,
                        tension: 0.3,
                        pointBackgroundColor: 'rgba(59, 130, 246, 1)',
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
        }

        // 初始化排名图表
        let rankingChart = null;
        function initRankingChart() {
            const ctx = document.getElementById('ranking-chart').getContext('2d');
            const groups = DataStore.getGroups();
            const students = DataStore.getStudents();
            
            // 计算每个小组的总积分
            const groupScores = groups.map(group => {
                let totalScore = 0;
                students.forEach(student => {
                    if (student.groupId === group.id) {
                        totalScore += student.score;
                    }
                });
                return {
                    name: group.name,
                    score: totalScore
                };
            });
            
            // 按积分排序，取前5名
            groupScores.sort((a, b) => b.score - a.score);
            const topGroups = groupScores.slice(0, 5);
            
            // 销毁现有图表
            if (rankingChart) {
                rankingChart.destroy();
            }
            
            // 创建新图表
            rankingChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: topGroups.map(g => g.name),
                    datasets: [{
                        label: '小组积分',
                        data: topGroups.map(g => g.score),
                        backgroundColor: 'rgba(16, 185, 129, 0.7)',
                        borderColor: 'rgba(16, 185, 129, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
        }

        // 刷新学生列表
        function refreshStudentsList() {
            const studentsContainer = document.getElementById('students-container');
            const students = DataStore.getStudents();
            const groups = DataStore.getGroups();
            const searchTerm = document.getElementById('searchInput').value.toLowerCase();
            
            // 过滤学生
            let filteredStudents = students;
            if (searchTerm) {
                filteredStudents = students.filter(student => 
                    student.name.toLowerCase().includes(searchTerm)
                );
            }
            
            // 按积分排序
            filteredStudents.sort((a, b) => b.score - a.score);
            
            if (filteredStudents.length === 0) {
                studentsContainer.innerHTML = `
                    <div class="text-center py-12 text-gray-500">
                        <i class="fa fa-search text-4xl mb-3"></i>
                        <p>没有找到匹配的学生</p>
                    </div>
                `;
                return;
            }
            
            // 生成HTML
            let html = `
                <table class="min-w-full divide-y divide-gray-200">
                    <thead>
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">排名</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">学生姓名</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">所属小组</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">积分</th>
                            <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
            `;
            
            filteredStudents.forEach((student, index) => {
                const group = groups.find(g => g.id === student.groupId) || { name: '未分组' };
                html += `
                    <tr class="hover:bg-gray-50 transition-colors">
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm font-medium text-gray-900">${index + 1}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm font-medium text-gray-900">${student.name}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-500">${group.name}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-900">${student.score}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                            <button onclick="showStudentDetail('${student.id}')" class="text-primary hover:text-primary/80 transition-colors">
                                详情
                            </button>
                        </td>
                    </tr>
                `;
            });
            
            html += `
                    </tbody>
                </table>
            `;
            
            studentsContainer.innerHTML = html;
        }

        // 刷新小组列表
        function refreshGroupsList() {
            const groupsContainer = document.getElementById('groups-container');
            const groupsList = document.getElementById('groupsList');
            const newStudentGroup = document.getElementById('newStudentGroup');
            const studentDetailGroup = document.getElementById('studentDetailGroup');
            
            const groups = DataStore.getGroups();
            const students = DataStore.getStudents();
            const searchTerm = document.getElementById('searchInput').value.toLowerCase();
            
            // 过滤小组
            let filteredGroups = groups;
            if (searchTerm) {
                filteredGroups = groups.filter(group => 
                    group.name.toLowerCase().includes(searchTerm)
                );
            }
            
            // 计算积分并排序
            const groupScores = filteredGroups.map(group => {
                const groupStudents = students.filter(student => student.groupId === group.id);
                let totalScore = 0;
                groupStudents.forEach(student => {
                    totalScore += student.score;
                });
                return { ...group, score: totalScore, memberCount: groupStudents.length };
            }).sort((a, b) => b.score - a.score);
            
            // 更新小组管理列表
            groupsList.innerHTML = '';
            groups.forEach(group => {
                const groupEl = document.createElement('div');
                groupEl.className = 'flex justify-between items-center p-2 border border-gray-200 rounded-lg';
                groupEl.innerHTML = `
                    <span>${group.name}</span>
                    <div class="flex gap-2">
                        <button onclick="showGroupStudents('${group.id}')" class="text-primary hover:text-primary/80">
                            <i class="fa fa-users"></i>
                        </button>
                        <button onclick="deleteGroup('${group.id}')" class="text-danger hover:text-danger/80">
                            <i class="fa fa-trash"></i>
                        </button>
                    </div>
                `;
                groupsList.appendChild(groupEl);
            });
            
            // 更新添加学生的小组选择框
            newStudentGroup.innerHTML = '<option value="">未分组</option>';
            studentDetailGroup.innerHTML = '<option value="">未分组</option>';
            
            groups.forEach(group => {
                const option1 = document.createElement('option');
                option1.value = group.id;
                option1.textContent = group.name;
                newStudentGroup.appendChild(option1);
                
                const option2 = document.createElement('option');
                option2.value = group.id;
                option2.textContent = group.name;
                studentDetailGroup.appendChild(option2);
            });
            
            // 更新小组列表视图
            if (groupScores.length === 0) {
                groupsContainer.innerHTML = `
                    <div class="text-center py-12 text-gray-500">
                        <i class="fa fa-search text-4xl mb-3"></i>
                        <p>没有找到匹配的小组</p>
                    </div>
                `;
                return;
            }
            
            // 生成HTML
            let html = `
                <table class="min-w-full divide-y divide-gray-200">
                    <thead>
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">排名</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">小组名称</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">成员数量</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">总积分</th>
                            <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
            `;
            
            groupScores.forEach((group, index) => {
                html += `
                    <tr class="hover:bg-gray-50 transition-colors">
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm font-medium text-gray-900">${index + 1}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm font-medium text-gray-900">${group.name}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-500">${group.memberCount}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-900">${group.score}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                            <button onclick="showGroupStudents('${group.id}')" class="text-primary hover:text-primary/80 transition-colors">
                                查看成员
                            </button>
                        </td>
                    </tr>
                `;
            });
            
            html += `
                    </tbody>
                </table>
            `;
            
            groupsContainer.innerHTML = html;
        }

        // 显示学生详情
        function showStudentDetail(studentId) {
            const students = DataStore.getStudents();
            const student = students.find(s => s.id === studentId);
            
            if (!student) return;
            
            document.getElementById('studentDetailId').value = student.id;
            document.getElementById('studentDetailName').value = student.name;
            document.getElementById('studentDetailScore').value = student.score;
            document.getElementById('studentDetailGroup').value = student.groupId || '';
            
            showModal('studentDetailModal');
        }

        // 保存学生积分
        function saveStudentScore() {
            const studentId = document.getElementById('studentDetailId').value;
            const newScore = parseInt(document.getElementById('studentDetailScore').value) || 0;
            const newGroupId = document.getElementById('studentDetailGroup').value;
            const reason = document.getElementById('scoreChangeReason').value;
            
            const students = DataStore.getStudents();
            const studentIndex = students.findIndex(s => s.id === studentId);
            
            if (studentIndex === -1) return;
            
            const oldScore = students[studentIndex].score;
            const studentName = students[studentIndex].name;
            const scoreChange = newScore - oldScore;
            
            // 检查是否允许负分
            const settings = DataStore.getSystemSettings();
            if (!settings.allowNegativeScores && newScore < 0) {
                showNotification('不允许积分出现负值', 'warning');
                return;
            }
            
            // 更新学生信息
            students[studentIndex].score = newScore;
            students[studentIndex].groupId = newGroupId;
            
            DataStore.saveStudents(students);
            
            // 添加历史记录
            if (scoreChange !== 0) {
                DataStore.addScoreHistory({
                    type: 'student',
                    targetId: studentId,
                    targetName: studentName,
                    change: scoreChange,
                    reason: reason,
                    oldScore: oldScore,
                    newScore: newScore
                });
                
                // 更新每日积分统计
                DataStore.updateDailyScore(new Date(), scoreChange);
            }
            
            hideModal('studentDetailModal');
            refreshStudentsList();
            refreshGroupsList();
            initScoreChart();
            initRankingChart();
            
            if (scoreChange !== 0) {
                showNotification(`学生积分已更新，变动: ${scoreChange > 0 ? '+' : ''}${scoreChange}`);
            } else {
                showNotification('学生信息已更新');
            }
        }

        // 确认删除学生
        function confirmDeleteStudent() {
            const studentName = document.getElementById('studentDetailName').value;
            
            if (confirm(`确定要删除学生"${studentName}"吗？此操作不可撤销。`)) {
                const studentId = document.getElementById('studentDetailId').value;
                DataStore.deleteStudent(studentId);
                
                hideModal('studentDetailModal');
                refreshStudentsList();
                refreshGroupsList();
                initScoreChart();
                initRankingChart();
                
                showNotification('学生已删除');
            }
        }

        // 添加学生
        function addStudent() {
            const studentName = document.getElementById('newStudentName').value.trim();
            const groupId = document.getElementById('newStudentGroup').value;
            
            if (!studentName) {
                showNotification('请输入学生姓名', 'warning');
                return;
            }
            
            // 创建新学生
            const newStudent = {
                id: generateId(),
                name: studentName,
                score: 0,
                groupId: groupId
            };
            
            DataStore.addStudent(newStudent);
            
            // 如果分配了小组，更新小组成员
            if (groupId) {
                const groups = DataStore.getGroups();
                const groupIndex = groups.findIndex(g => g.id === groupId);
                if (groupIndex !== -1) {
                    if (!groups[groupIndex].members) {
                        groups[groupIndex].members = [];
                    }
                    groups[groupIndex].members.push(newStudent.id);
                    DataStore.saveGroups(groups);
                }
            }
            
            // 清空输入框
            document.getElementById('newStudentName').value = '';
            
            refreshStudentsList();
            refreshGroupsList();
            
            showNotification(`学生"${studentName}"已添加`);
        }

        // 创建小组
        function createGroup() {
            const groupName = document.getElementById('newGroupName').value.trim();
            
            if (!groupName) {
                showNotification('请输入小组名称', 'warning');
                return;
            }
            
            // 创建新小组
            const newGroup = {
                id: generateId(),
                name: groupName,
                members: []
            };
            
            DataStore.createGroup(newGroup);
            
            // 清空输入框
            document.getElementById('newGroupName').value = '';
            
            refreshGroupsList();
            initRankingChart();
            
            showNotification(`小组"${groupName}"已创建`);
        }

        // 删除小组
        function deleteGroup(groupId) {
            const groups = DataStore.getGroups();
            const group = groups.find(g => g.id === groupId);
            
            if (!group) return;
            
            if (confirm(`确定要删除小组"${group.name}"吗？小组内的学生将变为未分组状态。`)) {
                DataStore.deleteGroup(groupId);
                
                refreshStudentsList();
                refreshGroupsList();
                initRankingChart();
                
                showNotification(`小组"${group.name}"已删除`);
            }
        }

        // 显示小组学生
        function showGroupStudents(groupId) {
            const groups = DataStore.getGroups();
            const students = DataStore.getStudents();
            const group = groups.find(g => g.id === groupId);
            
            if (!group) return;
            
            // 获取小组学生
            const groupStudents = students.filter(student => student.groupId === groupId);
            
            // 按积分排序
            groupStudents.sort((a, b) => b.score - a.score);
            
            let html = `
                <div class="mb-4">
                    <h3 class="text-lg font-medium text-gray-800">${group.name} (${groupStudents.length}名成员)</h3>
                    <p class="text-gray-500 text-sm">总积分: ${groupStudents.reduce((sum, student) => sum + student.score, 0)}</p>
                </div>
                
                <table class="min-w-full divide-y divide-gray-200">
                    <thead>
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">排名</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">学生姓名</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">积分</th>
                            <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
            `;
            
            groupStudents.forEach((student, index) => {
                html += `
                    <tr class="hover:bg-gray-50 transition-colors">
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm font-medium text-gray-900">${index + 1}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm font-medium text-gray-900">${student.name}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-900">${student.score}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                            <button onclick="showStudentDetail('${student.id}')" class="text-primary hover:text-primary/80 transition-colors">
                                详情
                            </button>
                        </td>
                    </tr>
                `;
            });
            
            if (groupStudents.length === 0) {
                html += `
                    <tr>
                        <td colspan="4" class="px-6 py-8 text-center text-gray-500">
                            该小组暂无成员
                        </td>
                    </tr>
                `;
            }
            
            html += `
                    </tbody>
                </table>
                
                <div class="mt-4">
                    <button id="backToGroupsBtn" class="bg-gray-200 hover:bg-gray-300 text-gray-800 px-4 py-2 rounded-lg transition-all duration-300 btn-effect">
                        返回小组列表
                    </button>
                </div>
            `;
            
            document.getElementById('groups-container').innerHTML = html;
            
            // 添加返回按钮事件
            document.getElementById('backToGroupsBtn').addEventListener('click', refreshGroupsList);
        }

        // 修改密码
        function changePassword() {
            const useCurrentPassword = !document.getElementById('currentPasswordSection').classList.contains('hidden');
            const currentPassword = useCurrentPassword ? document.getElementById('currentPassword').value : '';
            const teacherCode = !useCurrentPassword ? document.getElementById('modifyPasswordTeacherCode').value : '';
            const newPassword = document.getElementById('newPassword').value;
            const confirmPassword = document.getElementById('confirmPassword').value;
            const errorElement = document.getElementById('passwordError');
            
            // 验证输入
            errorElement.classList.add('hidden');
            
            if (useCurrentPassword && currentPassword !== DataStore.getPassword()) {
                errorElement.textContent = '当前密码不正确';
                errorElement.classList.remove('hidden');
                return;
            }
            
            if (!useCurrentPassword && teacherCode !== DataStore.getTeacherCode()) {
                errorElement.textContent = '教师口令不正确';
                errorElement.classList.remove('hidden');
                return;
            }
            
            if (newPassword.length < 6) {
                errorElement.textContent = '新密码长度至少为6位';
                errorElement.classList.remove('hidden');
                return;
            }
            
            if (newPassword !== confirmPassword) {
                errorElement.textContent = '两次输入的密码不一致';
                errorElement.classList.remove('hidden');
                return;
            }
            
            // 保存新密码
            DataStore.changePassword(newPassword);
            
            hideModal('changePasswordModal');
            showNotification('密码修改成功，请重新登录');
            
            // 返回登录界面
            document.getElementById('mainScreen').classList.add('hidden');
            document.getElementById('loginScreen').classList.remove('hidden');
            document.getElementById('loginPassword').value = '';
        }

        // 修改教师口令
        function changeTeacherCode() {
            const currentTeacherCode = document.getElementById('currentTeacherCode').value;
            const newTeacherCode = document.getElementById('newTeacherCode').value;
            const confirmTeacherCode = document.getElementById('confirmTeacherCode').value;
            const errorElement = document.getElementById('teacherCodeError');
            const successElement = document.getElementById('teacherCodeSuccess');
            
            // 验证输入
            errorElement.classList.add('hidden');
            successElement.classList.add('hidden');
            
            if (currentTeacherCode !== DataStore.getTeacherCode()) {
                errorElement.textContent = '当前教师口令不正确';
                errorElement.classList.remove('hidden');
                return;
            }
            
            if (newTeacherCode.length < 6) {
                errorElement.textContent = '新教师口令长度至少为6位';
                errorElement.classList.remove('hidden');
                return;
            }
            
            if (newTeacherCode !== confirmTeacherCode) {
                errorElement.textContent = '两次输入的教师口令不一致';
                errorElement.classList.remove('hidden');
                return;
            }
            
            // 保存新口令
            DataStore.changeTeacherCode(newTeacherCode);
            
            successElement.textContent = '教师口令修改成功';
            successElement.classList.remove('hidden');
            
            // 清空输入框
            document.getElementById('currentTeacherCode').value = '';
            document.getElementById('newTeacherCode').value = '';
            document.getElementById('confirmTeacherCode').value = '';
        }

        // 初始化时间范围
        function initTimeRange() {
            const now = new Date();
            const currentWeek = Math.ceil((now - new Date(now.getFullYear(), 0, 1)) / 604800000);
            const currentMonth = now.getMonth() + 1;
            const currentYear = now.getFullYear();
            const currentSemester = currentMonth <= 6 ? 1 : 2;
            
            document.getElementById('timeRangeDisplay').textContent = `本周 (第 ${currentWeek} 周)`;
            document.getElementById('currentPeriodDisplay').textContent = `本周 (第 ${currentWeek} 周)`;
            
            // 时间范围按钮事件
            document.querySelectorAll('.time-range-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    document.querySelectorAll('.time-range-btn').forEach(b => {
                        b.classList.remove('bg-primary', 'text-white');
                        b.classList.add('bg-gray-200', 'text-gray-700');
                    });
                    
                    this.classList.remove('bg-gray-200', 'text-gray-700');
                    this.classList.add('bg-primary', 'text-white');
                    
                    const range = this.getAttribute('data-range');
                    let displayText = '';
                    
                    switch (range) {
                        case 'week':
                            displayText = `本周 (第 ${currentWeek} 周)`;
                            break;
                        case 'month':
                            displayText = `${currentYear}年 第 ${currentMonth} 月`;
                            break;
                        case 'semester':
                            displayText = `${currentYear}年 第 ${currentSemester} 学期`;
                            break;
                        case 'year':
                            displayText = `${currentYear}年`;
                            break;
                    }
                    
                    document.getElementById('timeRangeDisplay').textContent = displayText;
                    document.getElementById('currentPeriodDisplay').textContent = displayText;
                });
            });
        }

        // 初始化事件监听
        function initEventListeners() {
            // 登录相关
            document.getElementById('loginBtn').addEventListener('click', function() {
                const password = document.getElementById('loginPassword').value;
                const errorElement = document.getElementById('loginError');
                
                if (password === DataStore.getPassword()) {
                    document.getElementById('loginScreen').classList.add('hidden');
                    document.getElementById('mainScreen').classList.remove('hidden');
                    errorElement.classList.add('hidden');
                    
                    // 初始化应用数据
                    refreshStudentsList();
                    refreshGroupsList();
                    initScoreChart();
                    initRankingChart();
                    initTimeRange();
                } else {
                    errorElement.textContent = '密码错误，请重试';
                    errorElement.classList.remove('hidden');
                }
            });
            
            // 忘记密码相关
            document.getElementById('forgotPasswordBtn').addEventListener('click', function() {
                showModal('forgotPasswordModal');
            });
            
            document.getElementById('closeForgotPasswordModal').addEventListener('click', function() {
                hideModal('forgotPasswordModal');
            });
            
            document.getElementById('verifyTeacherCodeBtn').addEventListener('click', function() {
                const code = document.getElementById('teacherCode').value;
                const errorElement = document.getElementById('forgotPasswordError');
                
                if (code === DataStore.getTeacherCode()) {
                    hideModal('forgotPasswordModal');
                    document.getElementById('loginScreen').classList.add('hidden');
                    document.getElementById('mainScreen').classList.remove('hidden');
                    
                    // 初始化应用数据
                    refreshStudentsList();
                    refreshGroupsList();
                    initScoreChart();
                    initRankingChart();
                    initTimeRange();
                } else {
                    errorElement.textContent = '教师口令错误，请重试';
                    errorElement.classList.remove('hidden');
                }
            });
            
            // 密码可见性切换
            document.getElementById('toggleLoginPassword').addEventListener('click', togglePasswordVisibility('loginPassword', 'toggleLoginPassword'));
            document.getElementById('toggleCurrentPassword').addEventListener('click', togglePasswordVisibility('currentPassword', 'toggleCurrentPassword'));
            document.getElementById('toggleModifyTeacherCode').addEventListener('click', togglePasswordVisibility('modifyPasswordTeacherCode', 'toggleModifyTeacherCode'));
            document.getElementById('toggleNewPassword').addEventListener('click', togglePasswordVisibility('newPassword', 'toggleNewPassword'));
            document.getElementById('toggleConfirmPassword').addEventListener('click', togglePasswordVisibility('confirmPassword', 'toggleConfirmPassword'));
            document.getElementById('toggleCurrentTeacherCode').addEventListener('click', togglePasswordVisibility('currentTeacherCode', 'toggleCurrentTeacherCode'));
            document.getElementById('toggleNewTeacherCode').addEventListener('click', togglePasswordVisibility('newTeacherCode', 'toggleNewTeacherCode'));
            document.getElementById('toggleConfirmTeacherCode').addEventListener('click', togglePasswordVisibility('confirmTeacherCode', 'toggleConfirmTeacherCode'));
            
            // 视图切换
            document.getElementById('studentsViewBtn').addEventListener('click', function() {
                document.getElementById('studentsViewBtn').classList.add('border-primary', 'text-primary');
                document.getElementById('studentsViewBtn').classList.remove('border-transparent', 'text-gray-500');
                document.getElementById('groupsViewBtn').classList.add('border-transparent', 'text-gray-500');
                document.getElementById('groupsViewBtn').classList.remove('border-primary', 'text-primary');
                
                document.getElementById('students-container').classList.remove('hidden');
                document.getElementById('groups-container').classList.add('hidden');
            });
            
            document.getElementById('groupsViewBtn').addEventListener('click', function() {
                document.getElementById('groupsViewBtn').classList.add('border-primary', 'text-primary');
                document.getElementById('groupsViewBtn').classList.remove('border-transparent', 'text-gray-500');
                document.getElementById('studentsViewBtn').classList.add('border-transparent', 'text-gray-500');
                document.getElementById('studentsViewBtn').classList.remove('border-primary', 'text-primary');
                
                document.getElementById('groups-container').classList.remove('hidden');
                document.getElementById('students-container').classList.add('hidden');
            });
            
            // 搜索功能
            document.getElementById('searchInput').addEventListener('input', function() {
                if (document.getElementById('students-container').classList.contains('hidden')) {
                    refreshGroupsList();
                } else {
                    refreshStudentsList();
                }
            });
            
            // 历史记录相关
            document.getElementById('historyBtn').addEventListener('click', function() {
                showModal('historyModal');
                updateHistoryDisplay();
            });
            
            document.getElementById('closeHistoryModal').addEventListener('click', function() {
                hideModal('historyModal');
            });
            
            document.getElementById('historyFilterType').addEventListener('change', updateHistoryDisplay);
            document.getElementById('historySearchInput').addEventListener('input', updateHistoryDisplay);
            
            document.getElementById('clearHistoryBtn').addEventListener('click', function() {
                if (confirm('确定要清空所有积分历史记录吗？此操作不可撤销。')) {
                    DataStore.clearScoreHistory();
                    updateHistoryDisplay();
                    showNotification('历史记录已清空');
                }
            });
            
            // 设置相关
            document.getElementById('settingsBtn').addEventListener('click', function() {
                showModal('settingsModal');
            });
            
            document.getElementById('closeSettingsModal').addEventListener('click', function() {
                hideModal('settingsModal');
            });
            
            // 修改密码相关
            document.getElementById('changePasswordBtn').addEventListener('click', function() {
                hideModal('settingsModal');
                showModal('changePasswordModal');
                
                // 重置表单
                document.getElementById('passwordError').classList.add('hidden');
                document.getElementById('currentPassword').value = '';
                document.getElementById('modifyPasswordTeacherCode').value = '';
                document.getElementById('newPassword').value = '';
                document.getElementById('confirmPassword').value = '';
            });
            
            document.getElementById('closeChangePasswordModal').addEventListener('click', function() {
                hideModal('changePasswordModal');
            });
            
            document.getElementById('backToSettingsFromPasswordBtn').addEventListener('click', function() {
                hideModal('changePasswordModal');
                showModal('settingsModal');
            });
            
            document.getElementById('savePasswordBtn').addEventListener('click', changePassword);
            
            // 验证方式切换
            document.getElementById('useCurrentPasswordBtn').addEventListener('click', function() {
                document.getElementById('currentPasswordSection').classList.remove('hidden');
                document.getElementById('teacherCodeSection').classList.add('hidden');
                
                this.classList.add('bg-primary', 'text-white');
                this.classList.remove('bg-gray-200', 'text-gray-700');
                document.getElementById('useTeacherCodeBtn').classList.add('bg-gray-200', 'text-gray-700');
                document.getElementById('useTeacherCodeBtn').classList.remove('bg-primary', 'text-white');
            });
            
            document.getElementById('useTeacherCodeBtn').addEventListener('click', function() {
                document.getElementById('teacherCodeSection').classList.remove('hidden');
                document.getElementById('currentPasswordSection').classList.add('hidden');
                
                this.classList.add('bg-primary', 'text-white');
                this.classList.remove('bg-gray-200', 'text-gray-700');
                document.getElementById('useCurrentPasswordBtn').classList.add('bg-gray-200', 'text-gray-700');
                document.getElementById('useCurrentPasswordBtn').classList.remove('bg-primary', 'text-white');
            });
            
            // 教师口令相关
            document.getElementById('changeTeacherCodeBtn').addEventListener('click', function() {
                hideModal('settingsModal');
                showModal('teacherCodeSettingsModal');
                
                // 重置表单
                document.getElementById('teacherCodeError').classList.add('hidden');
                document.getElementById('teacherCodeSuccess').classList.add('hidden');
                document.getElementById('currentTeacherCode').value = '';
                document.getElementById('newTeacherCode').value = '';
                document.getElementById('confirmTeacherCode').value = '';
            });
            
            document.getElementById('closeTeacherCodeSettingsModal').addEventListener('click', function() {
                hideModal('teacherCodeSettingsModal');
            });
            
            document.getElementById('backToSettingsFromTeacherCodeBtn').addEventListener('click', function() {
                hideModal('teacherCodeSettingsModal');
                showModal('settingsModal');
            });
            
            document.getElementById('saveTeacherCodeBtn').addEventListener('click', changeTeacherCode);
            
            // 积分规则相关
            document.getElementById('scoreRulesBtn').addEventListener('click', function() {
                hideModal('settingsModal');
                showModal('scoreRulesModal');
                initScoreRulesForm();
            });
            
            document.getElementById('closeScoreRulesModal').addEventListener('click', function() {
                hideModal('scoreRulesModal');
            });
            
            document.getElementById('saveScoreRulesBtn').addEventListener('click', saveScoreRules);
            
            // 清空数据相关
            document.getElementById('clearDataBtn').addEventListener('click', function() {
                if (confirm('确定要清空所有数据吗？此操作不可撤销，包括学生、小组和历史记录。')) {
                    const teacherCode = prompt('请输入教师口令以确认操作：');
                    
                    if (teacherCode === DataStore.getTeacherCode()) {
                        DataStore.clearAllData();
                        hideModal('settingsModal');
                        
                        refreshStudentsList();
                        refreshGroupsList();
                        initScoreChart();
                        initRankingChart();
                        updateHistoryDisplay();
                        
                        showNotification('所有数据已清空');
                    } else {
                        showNotification('教师口令不正确，操作已取消', 'error');
                    }
                }
            });
            
            // 导出数据
            document.getElementById('exportDataBtn').addEventListener('click', exportData);
            
            // 添加学生
            document.getElementById('addStudentBtn').addEventListener('click', addStudent);
            
            // 学生详情相关
            document.getElementById('closeStudentDetailModal').addEventListener('click', () => hideModal('studentDetailModal'));
            document.getElementById('increaseStudentScore').addEventListener('click', () => {
                const scoreInput = document.getElementById('studentDetailScore');
                scoreInput.value = parseInt(scoreInput.value || 0) + 1;
            });
            
            document.getElementById('decreaseStudentScore').addEventListener('click', () => {
                const scoreInput = document.getElementById('studentDetailScore');
                const currentScore = parseInt(scoreInput.value || 0);
                const settings = DataStore.getSystemSettings();
                
                if (settings.allowNegativeScores || currentScore > 0) {
                    scoreInput.value = currentScore - 1;
                }
            });
            
            document.getElementById('saveStudentScoreBtn').addEventListener('click', saveStudentScore);
            document.getElementById('deleteStudentBtn').addEventListener('click', confirmDeleteStudent);
            
            // 小组管理
            document.getElementById('createGroupBtn').addEventListener('click', createGroup);
        }

        // 初始化应用
        function initApp() {
            // 初始化数据存储
            DataStore.init();
            
            // 初始化事件监听
            initEventListeners();
            
            // 初始化积分规则下拉框
            const rules = DataStore.getScoreRules();
            const scoreChangeReason = document.getElementById('scoreChangeReason');
            
            scoreChangeReason.innerHTML = '';
            Object.keys(rules).forEach(reason => {
                const option = document.createElement('option');
                option.value = reason;
                option.textContent = reason;
                scoreChangeReason.appendChild(option);
            });
        }

        // 全局函数，供HTML中直接调用
        window.showStudentDetail = showStudentDetail;
        window.showGroupStudents = showGroupStudents;
        window.deleteGroup = deleteGroup;

        // 页面加载完成后初始化应用
        document.addEventListener('DOMContentLoaded', initApp);
    </script>
</body>
</html>
